import { TaskManager } from '../../utils/taskManager.js'

Page({
  data: {
    completedTasks: [], // 已完成任务列表
    loading: false, // 加载状态
    searchKeyword: '', // 搜索关键词
    showSearch: false, // 是否显示搜索栏
    sortType: 'completeTime_desc', // 排序类型
    sortOptions: [
      { value: 'completeTime_desc', label: '完成时间↓' },
      { value: 'completeTime_asc', label: '完成时间↑' },
      { value: 'createTime_desc', label: '创建时间↓' },
      { value: 'priority_asc', label: '优先级↑' },
      { value: 'title_asc', label: '标题A-Z' }
    ],
    filteredTasks: [], // 筛选后的任务列表
    batchMode: false, // 批量操作模式
    selectedTasks: [] // 选中的任务ID列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    console.log('已完成任务页面加载')
    this.loadCompletedTasks()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadCompletedTasks()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadCompletedTasks()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  /**
   * 加载已完成任务
   */
  loadCompletedTasks() {
    this.setData({ loading: true })
    
    try {
      const allTasks = TaskManager.getAllTasks()
      const completedTasks = allTasks
        .filter(task => task.status === 1)
        .map(task => ({
          ...task,
          formattedCompleteTime: this.formatTime(task.completeTime),
          formattedCreateTime: this.formatTime(task.createTime),
          priorityInfo: this.getPriorityInfo(task.priority)
        }))
      
      this.setData({
        completedTasks: completedTasks,
        loading: false
      })
      
      // 应用筛选和排序
      this.applyFiltersAndSort()
      
      console.log('已完成任务加载成功:', completedTasks.length)
    } catch (error) {
      console.error('加载已完成任务失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    }
  },

  /**
   * 应用筛选和排序
   */
  applyFiltersAndSort() {
    let filteredTasks = [...this.data.completedTasks]
    
    // 应用搜索筛选
    if (this.data.searchKeyword.trim()) {
      const keyword = this.data.searchKeyword.trim().toLowerCase()
      filteredTasks = filteredTasks.filter(task => 
        task.title.toLowerCase().includes(keyword) ||
        (task.note && task.note.toLowerCase().includes(keyword))
      )
    }
    
    // 应用排序
    filteredTasks = this.applySorting(filteredTasks)
    
    this.setData({ filteredTasks })
  },

  /**
   * 应用排序
   */
  applySorting(tasks) {
    const [field, order] = this.data.sortType.split('_')
    
    return [...tasks].sort((a, b) => {
      let aValue, bValue
      
      switch (field) {
        case 'completeTime':
        case 'createTime':
          aValue = a[field] || 0
          bValue = b[field] || 0
          break
        case 'priority':
          aValue = a.priority
          bValue = b.priority
          break
        case 'title':
          aValue = a.title.toLowerCase()
          bValue = b.title.toLowerCase()
          break
        default:
          return 0
      }
      
      if (order === 'asc') {
        return aValue > bValue ? 1 : aValue < bValue ? -1 : 0
      } else {
        return aValue < bValue ? 1 : aValue > bValue ? -1 : 0
      }
    })
  },

  /**
   * 获取优先级信息
   */
  getPriorityInfo(priority) {
    const priorityMap = {
      1: { text: '高', color: '#ff4757' },
      2: { text: '中', color: '#ffa502' },
      3: { text: '低', color: '#2ed573' }
    }
    return priorityMap[priority] || priorityMap[2]
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    const date = new Date(timestamp)
    const now = new Date()
    const diff = now - date
    
    if (diff < 60000) { // 1分钟内
      return '刚刚'
    } else if (diff < 3600000) { // 1小时内
      return Math.floor(diff / 60000) + '分钟前'
    } else if (diff < 86400000) { // 1天内
      return Math.floor(diff / 3600000) + '小时前'
    } else if (diff < 2592000000) { // 30天内
      return Math.floor(diff / 86400000) + '天前'
    } else {
      return date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate()
    }
  },

  /**
   * 切换搜索栏显示
   */
  toggleSearch() {
    const showSearch = !this.data.showSearch
    this.setData({
      showSearch: showSearch
    })
    
    if (!showSearch) {
      this.setData({ searchKeyword: '' })
      this.applyFiltersAndSort()
    }
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    const keyword = e.detail.value
    this.setData({ searchKeyword: keyword })
    this.applyFiltersAndSort()
  },

  /**
   * 清空搜索
   */
  clearSearch() {
    this.setData({ searchKeyword: '' })
    this.applyFiltersAndSort()
  },

  /**
   * 切换排序方式
   */
  onSortChange(e) {
    const sortIndex = e.detail.value
    const sortType = this.data.sortOptions[sortIndex].value
    
    this.setData({ sortType: sortType })
    this.applyFiltersAndSort()
    
    const sortLabel = this.data.sortOptions[sortIndex].label
    wx.showToast({
      title: `按${sortLabel}排序`,
      icon: 'none',
      duration: 1000
    })
  },

  /**
   * 切换批量操作模式
   */
  toggleBatchMode() {
    const batchMode = !this.data.batchMode
    this.setData({
      batchMode: batchMode,
      selectedTasks: []
    })
    
    if (batchMode) {
      wx.showToast({
        title: '进入批量操作模式',
        icon: 'none'
      })
    }
  },

  /**
   * 切换任务选择状态
   */
  toggleTaskSelection(e) {
    const taskId = e.currentTarget.dataset.id
    const selectedTasks = [...this.data.selectedTasks]
    const index = selectedTasks.indexOf(taskId)
    
    if (index > -1) {
      selectedTasks.splice(index, 1)
    } else {
      selectedTasks.push(taskId)
    }
    
    this.setData({ selectedTasks })
  },

  /**
   * 批量恢复任务
   */
  batchRestore() {
    const selectedTasks = this.data.selectedTasks
    if (selectedTasks.length === 0) return
    
    wx.showModal({
      title: '批量恢复',
      content: `确定要恢复选中的 ${selectedTasks.length} 个任务吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...' })
          
          const result = TaskManager.batchOperation(selectedTasks, 'restore')
          wx.hideLoading()
          
          if (result.success) {
            wx.showToast({
              title: result.message,
              icon: 'success'
            })
            
            this.setData({
              batchMode: false,
              selectedTasks: []
            })
            
            this.loadCompletedTasks()
            wx.vibrateShort()
          } else {
            wx.showToast({
              title: result.message,
              icon: 'error'
            })
          }
        }
      }
    })
  },

  /**
   * 批量删除任务
   */
  batchDelete() {
    const selectedTasks = this.data.selectedTasks
    if (selectedTasks.length === 0) return
    
    wx.showModal({
      title: '批量删除',
      content: `确定要删除选中的 ${selectedTasks.length} 个任务吗？此操作不可恢复！`,
      confirmText: '删除',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' })
          
          const result = TaskManager.batchOperation(selectedTasks, 'delete')
          wx.hideLoading()
          
          if (result.success) {
            wx.showToast({
              title: result.message,
              icon: 'success'
            })
            
            this.setData({
              batchMode: false,
              selectedTasks: []
            })
            
            this.loadCompletedTasks()
          } else {
            wx.showToast({
              title: result.message,
              icon: 'error'
            })
          }
        }
      }
    })
  },

  /**
   * 点击任务项
   */
  onTaskTap(e) {
    if (this.data.batchMode) {
      this.toggleTaskSelection(e)
      return
    }
    
    const taskId = e.currentTarget.dataset.id
    console.log('查看任务详情:', taskId)
    
    // 跳转到任务详情页
    wx.navigateTo({
      url: `/pages/detail/detail?id=${taskId}`
    })
  },

  /**
   * 长按任务项
   */
  onTaskLongTap(e) {
    if (this.data.batchMode) return
    
    const taskId = e.currentTarget.dataset.id
    const task = this.data.filteredTasks.find(t => t.id === taskId)
    
    if (!task) return
    
    wx.showActionSheet({
      itemList: ['查看详情', '恢复为待完成', '删除任务'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.viewTaskDetail(task)
            break
          case 1:
            this.restoreTask(task)
            break
          case 2:
            this.deleteTask(task)
            break
        }
      }
    })
  },

  /**
   * 查看任务详情
   */
  viewTaskDetail(task) {
    wx.navigateTo({
      url: `/pages/detail/detail?id=${task.id}`
    })
  },

  /**
   * 恢复任务
   */
  restoreTask(task) {
    wx.showLoading({ title: '处理中...' })
    
    const result = TaskManager.uncompleteTask(task.id)
    wx.hideLoading()
    
    if (result.success) {
      wx.showToast({
        title: result.message,
        icon: 'success'
      })
      
      this.loadCompletedTasks()
      wx.vibrateShort()
    } else {
      wx.showToast({
        title: result.message,
        icon: 'error'
      })
    }
  },

  /**
   * 删除任务
   */
  deleteTask(task) {
    wx.showModal({
      title: '确认删除',
      content: `确定要删除任务"${task.title}"吗？此操作不可恢复！`,
      confirmText: '删除',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' })
          
          const result = TaskManager.deleteTask(task.id)
          wx.hideLoading()
          
          if (result.success) {
            wx.showToast({
              title: result.message,
              icon: 'success'
            })
            
            this.loadCompletedTasks()
          } else {
            wx.showToast({
              title: result.message,
              icon: 'error'
            })
          }
        }
      }
    })
  },

  /**
   * 清空所有已完成任务
   */
  clearAllCompleted() {
    if (this.data.completedTasks.length === 0) {
      wx.showToast({
        title: '暂无已完成任务',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '清空已完成任务',
      content: `确定要清空所有 ${this.data.completedTasks.length} 个已完成任务吗？此操作不可恢复！`,
      confirmText: '清空',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '清空中...' })
          
          const taskIds = this.data.completedTasks.map(task => task.id)
          const result = TaskManager.batchOperation(taskIds, 'delete')
          wx.hideLoading()
          
          if (result.success) {
            wx.showToast({
              title: '清空成功',
              icon: 'success'
            })
            
            this.loadCompletedTasks()
          } else {
            wx.showToast({
              title: '清空失败',
              icon: 'error'
            })
          }
        }
      }
    })
  }
}) 